#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <errno.h>
#include "../mars/mutex_lock.h"

using namespace mars;

class Counter {
    public:
        Counter(): _count(0) {};
        int value() {
            MutexLockGuard guard(_lock);
            return _count;
        }
        int get_and_increase() {
            MutexLockGuard guard(_lock);
            int tmp = _count++;
            return tmp;
        }
    private:
        int _count;
        MutexLock _lock;
};

Counter counter;

void* run(void*) {
    int i = 0;
    for (; i < 10; ++i) {
        std::cout << "tid:" << pthread_self()  << ", count:" << counter.get_and_increase() << std::endl;
        usleep(0);
    }
}

#define THREAD_NUM 100

int main() {
    int i = 0;
    pthread_t tid[THREAD_NUM];

    for (; i < THREAD_NUM; ++i) {
        int ret = pthread_create(&tid[i], NULL, run, NULL);
        if (ret != 0) {
            errno = ret;
            perror("pthread_create");
            exit(1);
        }
        std::cout << "tid[" << i << "]:" << tid[i] << std::endl;
    }

    for (i = 0; i < THREAD_NUM; ++i) {
        pthread_join(tid[i], NULL);
    }

    std::cout << "---------- End -----------" << std::endl;
}
